//
//  FreeQuoteViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/23.
//

import UIKit
import Photos
import AliyunOSSiOS
import HXPhotoPicker
import JXPhotoBrowser

class FreeQuoteViewController: BaseViewController {
    var tableView: BaseTableView!
    var dataModel: FreeQuoteModel!
    var carMileageRange = 0//里程范围
    var carQuality = 0//车辆状况
    var ownerNum = 0//主人数量
    var stepDiagramArray = NSMutableArray()
    var selectAssets: [PhotoAsset] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("get_ree_quote", comment: "获取免费报价")
        self.view.backgroundColor = Theme.F5Color
        self.inintTableView()
        self.dealStepDiagramData()
    }

    func inintTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .grouped)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.backgroundColor = .clear
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(StepDiagramTableViewCell.self, forCellReuseIdentifier: "StepDiagramTableViewCell")
        self.tableView.register(FreeQuoteTableViewCell.self, forCellReuseIdentifier: "FreeQuoteTableViewCell")
        self.view.addSubview(self.tableView)
        self.tableView.tableFooterView = self.initFooterView()
    }
    
    func initFooterView() -> UIView{
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: TabbarHeight))
        bgView.backgroundColor = .clear
        
        let lastStepBtn = UIButton(frame: CGRect(x: 14, y: 10, width: 87, height: 46))
        lastStepBtn.layer.cornerRadius = 4
        lastStepBtn.layer.masksToBounds = true
        lastStepBtn.layer.borderWidth = 1
        lastStepBtn.layer.borderColor = Theme.mainColor.cgColor
        lastStepBtn.setTitle(MMLocalizedString("last_step", comment: "上一步"), for: .normal)
        lastStepBtn.backgroundColor = .white
        lastStepBtn.setTitleColor(Theme.mainColor, for: .normal)
        lastStepBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 14)
        lastStepBtn.addTarget(self, action: #selector(lastStepBtnAntion), for: .touchUpInside)
        bgView.addSubview(lastStepBtn)
       
        
        let submitBtn = UIButton(frame: CGRect(x: lastStepBtn.frame.maxX + 10, y: 10, width: kScreenWidth - 38 - 87, height: 46))
        submitBtn.layer.cornerRadius = 4
        submitBtn.layer.masksToBounds = true
        submitBtn.setTitle(MMLocalizedString("submit", comment: "提交"), for: .normal)
        submitBtn.backgroundColor = Theme.mainColor
        submitBtn.titleLabel?.font = UIFont(name: Theme.PingFangSCMedium, size: 14)
        submitBtn.setTitleColor(.white, for: .normal)
        submitBtn.addTarget(self, action: #selector(submitBtnAntion), for: .touchUpInside)
        bgView.addSubview(submitBtn)
      
        
        
        return bgView
    }
    
    
    
    //步骤说明图
    func dealStepDiagramData(){
        
        let dataModel = VideoVRPdfModel.init()
        dataModel.name = MMLocalizedString("car_platform", comment: "1、在Kool Car平台登记车辆资料")
        dataModel.image = "icon_step"
        dataModel.content = MMLocalizedString("provide_photos", comment: "·尽量提供相片。")
        dataModel.content1 = MMLocalizedString("accurate_the_quotation", comment: "·你提供的资料越详细，报价越准确。")
        dataModel.content2 = ""
        
        let dataModelOne = VideoVRPdfModel.init()
        dataModelOne.name = MMLocalizedString("provides_quotation", comment: "2、销售顾问提供报价")
        dataModelOne.image = "icon_step_one"
        dataModelOne.content = MMLocalizedString("model_the_market", comment: "·帮你比较市场上相同车辆型号的市场价格。")
        dataModelOne.content1 = MMLocalizedString("day_quote_guarantee", comment: "·24小时内提供最高报价和15天报价保证。")
        dataModelOne.content2 = ""
        
        let dataModelTwo = VideoVRPdfModel.init()
        dataModelTwo.name = MMLocalizedString("close_the_deal", comment: "3、销售顾问帮你完成交易")
        dataModelTwo.image = "icon_step_Two"
        dataModelTwo.content = MMLocalizedString("car_inspection", comment: "·联络你到车行验车。")
        dataModelTwo.content1 = MMLocalizedString("transaction_procedures", comment: "·帮你完成全部交易手续。")
        dataModelTwo.content2 = MMLocalizedString("express_transfer", comment: "·安排特快转帐。")
        
        self.stepDiagramArray.add(dataModel)
        self.stepDiagramArray.add(dataModelOne)
        self.stepDiagramArray.add(dataModelTwo)
        
    }
    
    //MARK: -Reuqest
    func uploadRequest() {
        var param = NSMutableDictionary() as! [String: Any]
        param["carBrand"] = self.dataModel.carBrand
        param["carStyle"] = self.dataModel.carStyle
        param["carDate"]  = self.dataModel.carDate
        param["carMileageRange"] = "\(self.carMileageRange)"//里程范围
        param["carQuality"] = "\(self.carQuality)"//车辆状况
        param["ownerNum"] = "\(self.ownerNum)"//主人数量
       
        if self.dataModel.picures != nil && (self.dataModel.picures ?? []).count > 0{
            let tempurl = self.dataModel.picures?.compactMap { obj in
                return obj.url
            }
            param["picures"] = (tempurl! as NSArray).componentsJoined(by: ",") //图片
        }
        
        if self.dataModel.shortUrl != nil && self.dataModel.shortUrl != ""{
            param["shortUrl"] = self.dataModel.shortUrl
        }
        
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.recycleOrderSave(param: param), objectType: CommondResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                let vc = FreeQuoteSucceedViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
        
    }
    
    
    ///=========================
    ///上传照视频
    @objc func uploadBusinessImgStep(model: UpLoadImgModel){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getOSSToken, objectType: GetOssTokenModel.self, finished: { (response) in
            let resultObj = response as! GetOssTokenModel
            if resultObj.code == "1"{
                self.uploadImageToAliyunOSS(ossModel: resultObj.data!, model: model)
            }
        }) { (error) in
          
            printLog(error)
        }
    }
    
    func uploadImageToAliyunOSS(ossModel: GetTokenDataModel, model: UpLoadImgModel) {
        guard let url = URL(string: model.url ?? "") else {
            return
        }
        let endPoint = String(format: "http://%@.aliyuncs.com/", ossModel.region ?? "")
        let config = OSSClientConfiguration.init()
        let credential = OSSStsTokenCredentialProvider.init(accessKeyId: ossModel.accessKeyId ?? "", secretKeyId: ossModel.accessKeySecret ?? "", securityToken: ossModel.securityToken ?? "")
        let client = OSSClient.init(endpoint: endPoint, credentialProvider: credential, clientConfiguration: config)
        let put = OSSPutObjectRequest.init()
        put.uploadingFileURL = url
        put.bucketName = ossModel.bucketName ?? ""
        put.objectKey = String(format: "%@_%d.%@",
                               ossModel.fileDir ?? "",
                               XTManageCenter.getDateTimeStringNow(format: "yyyyMMddHHmmss"),
                               model.backstamp ?? "")
       //put.uploadingData = tempData
       
        let putTask = client.putObject(put)
        putTask.waitUntilFinished()
        if (putTask.error == nil) {
            printLog("上传成功")
            let resultUrl = client.presignPublicURL(withBucketName: ossModel.bucketName ?? "", withObjectKey: put.objectKey)
            self.dataModel.shortUrl = (resultUrl.result as? String)
            self.tableView.reloadData()
            printLog(resultUrl.result as? String)
            
        }else{
            printLog("上传失败")
         
        }
        putTask.continue(successBlock: {res in
            printLog(res)
            
        })
    }
    
    
    
    
    
    func jumpToLogin(){
       guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
           return
       }
       let vc = LoginViewController()
       let loginNavi = BaseNavigationController.init(rootViewController: vc)
       loginNavi.modalPresentationStyle = .fullScreen
       tabbarVC.present(loginNavi, animated: true)
   }
    
    //上一步
    @objc func lastStepBtnAntion(){
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func submitBtnAntion(){
        
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        
        //里程
        if self.dataModel.mileage == "" || self.dataModel.mileage == nil {
            self.dataModel.emptyMileag = MMLocalizedString("please_select_vehicle_mileage", comment: "请选择车辆里程")
        }else{
            self.dataModel.emptyMileag = ""
        }
        
        //车辆状况
        if self.dataModel.condition == "" || self.dataModel.condition == nil{
            self.dataModel.emptyVehicle  = MMLocalizedString("please_select_vehicle_status", comment: "请选择车辆状况")
            
        }else{
            self.dataModel.condition = ""
        }
        
        //车主数
        if self.dataModel.characteristic == "" || self.dataModel.characteristic == nil{
            self.dataModel.emptyCharac = MMLocalizedString("please_select_first_number", comment: "请选择首数")
        }else{
            self.dataModel.characteristic = ""
        }
        
        self.tableView.reloadData()
                
        if self.dataModel.mileage != nil && self.dataModel.condition != nil && self.dataModel.characteristic != nil {
            self.uploadRequest()
        }
  
    }
    
 
}
extension FreeQuoteViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "StepDiagramTableViewCell", for: indexPath) as! StepDiagramTableViewCell
            if self.stepDiagramArray.count > 0{
                cell.setDataArray(dataArray: self.stepDiagramArray as! [VideoVRPdfModel])
            }
            return cell
       
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "FreeQuoteTableViewCell", for: indexPath) as! FreeQuoteTableViewCell
            cell.delegate = self
            if self.dataModel != nil{
                cell.setModel(model: self.dataModel)
            }
            return cell
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
          headerView.backgroundColor = .clear
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .clear
        return footerView
    }
  
}

extension FreeQuoteViewController: FreeQuoteTableViewCellDelegate{
    func selectAllImage(selectImage: [UpLoadImgModel], hh: CGFloat) {
        self.dataModel.picures = selectImage
        self.dataModel.picuresHH = hh
        
        self.tableView.reloadData()
    }
    
    func selectType(selectIndex: NSInteger) {
        switch selectIndex {
        case 100:
            self.didSelectCarMileage()
        case 101:
            self.didSelectTheVehicles()
        case 102:
            self.didSelectCarNumber()
        case 103:
            if  self.dataModel.shortImage != nil{//视频播放
                let vc = VideoViewController()
                vc.videoUrl = self.dataModel.shortUrl ?? ""
                self.navigationController?.pushViewController(vc, animated: true)
            }else{//选择视频
                self.pushPicker()
            }
           
        default://104删除视频
            self.dataModel.shortImage = nil
            self.dataModel.shortUrl = ""
            self.selectAssets = []
            self.tableView.reloadData()
        }
    }
    
    
    
    
    
    ///里程
    func didSelectCarMileage() {
        let vc = MHPickerSheetView()
        vc.modalPresentationStyle = .overFullScreen
        vc.titleStr = MMLocalizedString("mileage", comment: "里程")
        vc.dataArray = [MMLocalizedString("Less_than_thousand", comment: "少于10,000公里")
                        ,MMLocalizedString("thousand_to_Threet", comment: "10,001 至 30,000 公里"),
                        MMLocalizedString("threet_to_six", comment: "30,001 至 60,000 公里"),
                        MMLocalizedString("sixthousand_ninethousand", comment: "60,001 至 90,000 公里"),
                        MMLocalizedString("ninethousand_above", comment: "90,001公里或以上")]
        vc.selectItem = self.dataModel?.mileage
        vc.callBack = {[weak self] (brandItem, vIndex, configFlag) in
            guard configFlag else {
                //取消
                return
            }
            self?.carMileageRange = vIndex
            self?.dataModel?.mileage = brandItem as? String
            self?.tableView.reloadData()
           
        }
        self.present(vc, animated: false, completion: nil)
    }
    
    
    ///车辆状况
    func didSelectTheVehicles() {
        let vc = MHPickerSheetView()
        vc.modalPresentationStyle = .overFullScreen
        vc.titleStr = MMLocalizedString("vehicle_condition", comment: "车辆状况")
        vc.dataArray = [MMLocalizedString("excellent", comment: "优质"),MMLocalizedString("good", comment: "良好"),
                        MMLocalizedString("fair", comment: "一般"),
                        MMLocalizedString("damaged", comment: "损坏")]
        vc.selectItem = self.dataModel?.condition
        vc.callBack = {[weak self] (brandItem, vIndex, configFlag) in
            guard configFlag else {
                //取消
          
                return
            }
            self?.carQuality = vIndex
            self?.dataModel?.condition = (brandItem as! String)
            self?.tableView.reloadData()
        }
        self.present(vc, animated: false, completion: nil)
    }
    

    ///车主数
    func didSelectCarNumber() {
        let vc = MHPickerSheetView()
        vc.modalPresentationStyle = .overFullScreen
        vc.titleStr = MMLocalizedString("characteristic", comment: "首数")
        vc.dataArray = [MMLocalizedString("none", comment: "没有"),MMLocalizedString("one", comment: "1个"),
                        MMLocalizedString("two", comment: "2个"),
                        MMLocalizedString("three", comment: "3个"),
                        MMLocalizedString("four", comment: "4 或以上")]
        if self.dataModel?.characteristic == ""  {
            vc.selectItem = "0"
        }else{
            vc.selectItem = self.dataModel?.characteristic
        }
        vc.callBack = {[weak self] (brandItem, vIndex, configFlag) in
            guard configFlag else {
                //取消
                return
            }
            self?.ownerNum = vIndex
            self?.dataModel?.characteristic = brandItem as? String
            self?.tableView.reloadData()
        }
        self.present(vc, animated: false, completion: nil)
    }
    
    
    func pushPicker(){
        //判断相册权限 放在这里， 因为插件第一次判断时，展示空白
        PHPhotoLibrary.requestAuthorization({ (firstStatus) in
            let result = (firstStatus == .authorized)
            if result {
                //允许APP访问相册
                DispatchQueue.main.async {
                    var config = PickerConfiguration.default
                    config.languageType = XTManageCenter.getHXPhotoPickerLanguage()
                    config.modalPresentationStyle = .fullScreen
                    config.allowSelectedTogether = false
                    config.maximumSelectedCount = 1
                    config.selectOptions = [.video]
                    config.photoList.allowAddCamera = false
                    
                    
                    let pickerController = PhotoPickerController.init(picker: config)
                    pickerController.pickerDelegate = self
                    pickerController.autoDismiss = true
                    // 当前被选择的资源对应的 PhotoAsset 对象数组
                    pickerController.selectedAssetArray = self.selectAssets
                    self.present(pickerController, animated: true)
                }
            } else {
                DispatchQueue.main.async {
                    self.alert()
                }
            }
        })
    }
    
    
    func alert() {
        let alert = UIAlertController(title:MMLocalizedString("app_cannot_album", comment: "App无法使用相册功能"), message: MMLocalizedString("setting_album_path", comment: "请在设置-隐私-相机中允许访问相册"), preferredStyle: .alert)
        let cancelAntion = UIAlertAction(title: MMLocalizedString("cancel", comment: "取消"), style: .default, handler: nil)
        let setAnion = UIAlertAction(title: MMLocalizedString("setting", comment: "设置"), style: .default) { (action) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
            }
        }
        alert.addAction(cancelAntion)
        alert.addAction(setAnion)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
 
    
}

//相册
extension FreeQuoteViewController: PhotoPickerControllerDelegate{
    func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        guard let asset = result.photoAssets.first?.phAsset else {
            return
        }
        PHImageManager.default().requestImage(for: asset, targetSize: CGSize.init(width: 80, height: 80), contentMode: .default, options: nil) { image, any in
            self.dataModel.shortImage = image
        }
        pickerController.dismiss(true) {
            self.selectAssets = result.photoAssets
            let videoModel = UpLoadImgModel.init()
             result.photoAssets.getVideoURL { urls in
                   var file = ""
                 for (_, value) in urls.enumerated() {
                     file = value.absoluteString
                 }
                 if let url = URL(string: file), url.isFileURL {
                     let filePath = url.path//文件路径
                     videoModel.url = filePath
                     let stamp = videoModel.url?.components(separatedBy: ".").last
                     videoModel.backstamp = stamp
                     let photoModel = result.photoAssets[0]
                     let allMB = self.convertToMB(photoModel.fileSize)
                     if allMB  > 300 {
                         self.view.makeToast(message: MMLocalizedString("videos_must_not_exceed ", comment: "上传视频大小不得超过300MB"))
                         return
                     }
                     self.uploadBusinessImgStep(model: videoModel)
                 } else {
                     print("无效的文件路径")
                 }
            }
        }
        
    }
    
    
    //int转MB
    func convertToMB(_ value: Int) -> Int {
        let mbValue = Double(value) / 1024 / 1024
        return Int(mbValue)
    }

   
    func pickerController(didCancel pickerController: PhotoPickerController) {
        pickerController.dismiss(animated: true, completion: nil)
    }
}
